package com.hhw.aidlclient;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;

import com.hhw.aidlservice.IAidlInterface;
import com.hhw.aidlservice.IServiceListener;

public class MainActivity extends Activity {


    private IAidlInterface mBinder = null;
    private final IServiceListener listener = new IServiceListener.Stub(){
        @Override
        public void onServiceMsg(String msg) throws RemoteException {
            System.out.println("客户端收到服务端的信息："+msg);
        }
    };

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBinder = IAidlInterface.Stub.asInterface(service);
            System.out.println("connect success");

            //连接成功后注册监听
            try {
                mBinder.addListener(listener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("disconnect");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.sendMsgBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (mBinder != null){
                        mBinder.onClientMsg("这是一条来自客户端的消息");
                    }else{
                        System.out.println("未连接服务端");
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.hhw.aidlservice"
                ,"com.hhw.aidlservice.MService"));
        bindService(intent,mServiceConnection,BIND_AUTO_CREATE);
        //绑定服务，第三个参数为如果服务未启动，则启动服务
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            mBinder.removeListener(listener);//解绑之前，取消监听
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        unbindService(mServiceConnection);
    }
}